import axios from 'axios';

/**
 * 新的流量数据查询工具
 * 支持新的第三方接口数据格式
 */
async function newFlowdata(ck) {
  // 构建请求体
  let config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: 'https://m.client.10010.com/servicequerybusiness/operationservice/queryOcsPackageFlowLeftContentRevisedInJune',
    headers: { 
      'accept': 'application/json, text/plain, */*', 
      'content-type': 'application/x-www-form-urlencoded', 
      'accept-encoding': 'gzip, deflate', 
      'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 
      'cookie': ck || ''
    }
  };

  try {
    // 发送请求
    const response = await axios.request(config);
    
    // 解析响应数据
    const data = response.data;
    
    // 处理新的数据格式
    if (data && data.resources) {
      return processNewDataFormat(data);
    }
    
    return data;
  } catch (error) {
    console.error('新流量数据查询失败:', error);
    throw error;
  }
}

/**
 * 处理新的数据格式
 * 将新格式转换为兼容现有系统的格式，保留每一项详细信息
 */
function processNewDataFormat(data) {
  const { packageName, resources } = data;
  
  // 初始化流量统计
  let generalTotal = 0;
  let generalUsed = 0;
  let generalRemaining = 0;
  let directedTotal = 0;
  let directedUsed = 0;
  let directedRemaining = 0;
  let otherTotal = 0;
  let otherUsed = 0;
  let otherRemaining = 0;
  
  // 存储每一项详细信息
  const generalFlowDetails = [];
  const directedFlowDetails = [];
  const otherFlowDetails = [];
  const voiceDetails = [];
  const smsDetails = [];
  
  // 处理流量资源
  const flowResource = resources.find(r => r.type === 'flow');
  if (flowResource && flowResource.details) {
    flowResource.details.forEach(detail => {
      const total = parseFloat(detail.total) || 0;
      const used = parseFloat(detail.use) || 0;
      const remain = parseFloat(detail.remain) || 0;
      
      // 构建详细信息对象
      const detailInfo = {
        name: detail.addUpItemName,
        total: total,
        used: used,
        remaining: remain,
        flowType: detail.flowType,
        endDate: detail.endDate,
        feePolicyName: detail.feePolicyName,
        usedPercent: detail.usedPercent,
        addupItemCode: detail.addupItemCode,
        feePolicyId: detail.feePolicyId,
        resourceType: detail.resourceType,
        realresourcetype: detail.realresourcetype
      };
      
      // 根据流量类型分类
      if (detail.flowType === '1') {
        // 通用流量
        generalTotal += total;
        generalUsed += used;
        generalRemaining += remain;
        generalFlowDetails.push(detailInfo);
      } else if (detail.flowType === '2') {
        // 定向流量
        directedTotal += total;
        directedUsed += used;
        directedRemaining += remain;
        directedFlowDetails.push(detailInfo);
      } else if (detail.flowType === '3') {
        // 其他类型流量
        otherTotal += total;
        otherUsed += used;
        otherRemaining += remain;
        otherFlowDetails.push(detailInfo);
      }
    });
  }
  
  // 处理语音资源
  const voiceResource = resources.find(r => r.type === 'Voice');
  let voiceTotal = 0;
  let voiceUsed = 0;
  let voiceRemaining = 0;
  
  if (voiceResource && voiceResource.details) {
    voiceResource.details.forEach(detail => {
      const total = parseInt(detail.total) || 0;
      const used = parseInt(detail.use) || 0;
      const remain = parseInt(detail.remain) || 0;
      
      voiceTotal += total;
      voiceUsed += used;
      voiceRemaining += remain;
      
      voiceDetails.push({
        name: detail.addUpItemName,
        total: total,
        used: used,
        remaining: remain,
        endDate: detail.endDate,
        feePolicyName: detail.feePolicyName,
        usedPercent: detail.usedPercent,
        addupItemCode: detail.addupItemCode,
        feePolicyId: detail.feePolicyId,
        resourceType: detail.resourceType,
        realresourcetype: detail.realresourcetype
      });
    });
  }
  
  // 处理短信资源
  const smsResource = resources.find(r => r.type === 'smsList');
  let smsTotal = 0;
  let smsUsed = 0;
  let smsRemaining = 0;
  
  if (smsResource && smsResource.details) {
    smsResource.details.forEach(detail => {
      const total = parseInt(detail.total) || 0;
      const used = parseInt(detail.use) || 0;
      const remain = parseInt(detail.remain) || 0;
      
      smsTotal += total;
      smsUsed += used;
      smsRemaining += remain;
      
      smsDetails.push({
        name: detail.addUpItemName,
        total: total,
        used: used,
        remaining: remain,
        endDate: detail.endDate,
        feePolicyName: detail.feePolicyName,
        usedPercent: detail.usedPercent,
        addupItemCode: detail.addupItemCode,
        feePolicyId: detail.feePolicyId,
        resourceType: detail.resourceType,
        realresourcetype: detail.realresourcetype
      });
    });
  }
  
  // 构建兼容的数据格式
  const processedData = {
    packageName: packageName || '未知套餐',
    flowSumList: [
      {
        // 通用流量
        xcanusevalue: generalRemaining,
        xusedvalue: generalUsed,
        flowType: '1'
      },
      {
        // 定向流量
        xcanusevalue: directedRemaining,
        xusedvalue: directedUsed,
        flowType: '2'
      },
      {
        // 其他类型流量
        xcanusevalue: otherRemaining,
        xusedvalue: otherUsed,
        flowType: '3'
      }
    ],
    // 详细数据
    detailedData: {
      generalFlow: {
        total: generalTotal,
        used: generalUsed,
        remaining: generalRemaining,
        details: generalFlowDetails
      },
      directedFlow: {
        total: directedTotal,
        used: directedUsed,
        remaining: directedRemaining,
        details: directedFlowDetails
      },
      otherFlow: {
        total: otherTotal,
        used: otherUsed,
        remaining: otherRemaining,
        details: otherFlowDetails
      },
      voice: {
        total: voiceTotal,
        used: voiceUsed,
        remaining: voiceRemaining,
        details: voiceDetails
      },
      sms: {
        total: smsTotal,
        used: smsUsed,
        remaining: smsRemaining,
        details: smsDetails
      }
    },
    // 原始数据保留
    originalData: data
  };
  
  return processedData;
}

/**
 * 获取流量详情信息
 * 返回更详细的流量使用情况
 */
function getTrafficDetails(data) {
  if (!data || !data.resources) {
    return null;
  }
  
  const flowResource = data.resources.find(r => r.type === 'flow');
  if (!flowResource || !flowResource.details) {
    return null;
  }
  
  return flowResource.details.map(detail => ({
    name: detail.addUpItemName,
    total: parseFloat(detail.total) || 0,
    used: parseFloat(detail.use) || 0,
    remaining: parseFloat(detail.remain) || 0,
    flowType: detail.flowType,
    endDate: detail.endDate,
    feePolicyName: detail.feePolicyName,
    usedPercent: detail.usedPercent
  }));
}

export { newFlowdata, processNewDataFormat, getTrafficDetails };
